package com.mingyizhudao.app.view.home;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.dixiang.framework.common.QJNetUICallback;
import com.dixiang.framework.common.QjResult;
import com.dixiang.framework.utils.Utils;
import com.dixiang.framework.widget.LoadingDialog;
import com.google.gson.reflect.TypeToken;
import com.mingyizhudao.app.R;
import com.mingyizhudao.app.http.DataUtils;
import com.mingyizhudao.app.utils.CommonUtils;
import com.mingyizhudao.app.utils.Constants;
import com.mingyizhudao.app.utils.IntentHelper;
import com.mingyizhudao.app.view.MYBaseFragment;
import com.mingyizhudao.app.view.MainActivity;
import com.mingyizhudao.app.view.WebViewActivity;
import com.mingyizhudao.app.view.WebViewWithBackActivity;
import com.mingyizhudao.app.view.booking.FastBookingActivity;
import com.mingyizhudao.app.view.doctor.DoctorListActivity;
import com.mingyizhudao.app.view.home.adapter.AdViewPagerAdapter;
import com.mingyizhudao.app.view.home.bean.BannerEntity;
import com.mingyizhudao.app.view.home.bean.DisNavsEntity;
import com.mingyizhudao.app.view.home.bean.ScalpelEntity;
import com.mingyizhudao.app.view.search.SearchActivity;
import com.mingyizhudao.app.widget.AdView;
import com.renn.rennsdk.param.GetAppParam;

public class HomeFragment extends MYBaseFragment {

	private Context context;
	private ScalpelEntity scalpelEntity;
	
	private ScalpelEntity scalpelEntity2;
	private Map<String,DisNavsEntity> mapDisNav = new HashMap<String , DisNavsEntity>();
	private LinearLayout ll_bottom ;
	private Handler handler = new Handler();
	private AdViewPagerAdapter mCounselViewPagerAdapter;
	private AdView advice_viewpager;
	
	private ViewPager dept_viewpager;
	private DeptPageAdapter deptPageAdapter;
    private ImageView iv_1,iv_2;//,iv_3
    private ArrayList<View> pageViews; 
    
    private static final String deptData = "Deptcategorydisease";
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View mView = inflater.inflate(R.layout.fragment_home, container, false);
		initView(mView);
		loadInitData();
		return mView;
	}

	private void loadInitData() {
		try {
			if (scalpelEntity == null || Constants.IS_SCALPEL_NEAD_REFRESH||scalpelEntity2 == null) {
				try {
					scalpelEntity = (ScalpelEntity) Utils
							.getDataFromCache(HomeFragment.class
									.getSimpleName());
					scalpelEntity2 = (ScalpelEntity) Utils.getDataFromCache(deptData);
					
				} catch (Exception ex) {
					ex.printStackTrace();
				}


				if (scalpelEntity != null) {
					 ll_bottom.setVisibility(View.VISIBLE);
					List<BannerEntity> banners = scalpelEntity.getBanners();
//					putMap(scalpelEntity.getDisNavs());
					mCounselViewPagerAdapter = new AdViewPagerAdapter(context,banners);
					
					
				}
				
				if (scalpelEntity2 != null) {
					
					putMap(scalpelEntity2.getDisNavs());
					deptPageAdapter = new DeptPageAdapter();
				}
				doNet();
			}
			
			if (mCounselViewPagerAdapter != null) {
				advice_viewpager.stopAutoCycle();
				advice_viewpager.setAdapter(mCounselViewPagerAdapter);
				advice_viewpager.startAutoCycle();
			}

			if (deptPageAdapter != null) {
				dept_viewpager.setAdapter(deptPageAdapter);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if (!hidden) {
			if (scalpelEntity==null||scalpelEntity2==null) {
				doNet();
			}
		}
		
	}
	
	@Override
	public void onResume() {
		super.onResume();
	}
	
	@Override
	public void initHeaderView() {
		setTopViewIsShow(true);
		clearTitle();
		hidHeaderView();
	}

	/*
	 * 初始化界面
	 */
	private void initView(View mView) {

		context = getActivity();
	    ll_bottom = (LinearLayout) mView.findViewById(R.id.ll_bottom);
	    ll_bottom.setVisibility(View.GONE);
	    
	    mView.findViewById(R.id.search).setOnClickListener(onClickListener);	
	    
		mView.findViewById(R.id.go_doctor).setOnClickListener(onClickListener);
		mView.findViewById(R.id.go_benefit).setOnClickListener(onClickListener);
		mView.findViewById(R.id.go_fast_booking).setOnClickListener(onClickListener);
		
		
		
		
		advice_viewpager = (AdView) mView.findViewById(R.id.advice_viewpager);
		advice_viewpager.setTitleViewVisibility(View.GONE);
		advice_viewpager.setmCanScroll(false);
		advice_viewpager.setIndicatorGravity(Gravity.CENTER_HORIZONTAL);
		advice_viewpager.setDuration(3000);

		advice_viewpager.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return false;
			}
		});
		
		
		View view1 = LayoutInflater.from(context).inflate(R.layout.home_dept_first, null);
		
		view1.findViewById(R.id.dpt_waike).setOnClickListener(onClickListener);
		view1.findViewById(R.id.dpt_guke).setOnClickListener(onClickListener);
		view1.findViewById(R.id.dpt_shenjingwaike).setOnClickListener(onClickListener);
		view1.findViewById(R.id.dpt_miniaowaike).setOnClickListener(onClickListener);
		view1.findViewById(R.id.dpt_xiongwaike).setOnClickListener(onClickListener);
		view1.findViewById(R.id.dpt_xinxueguanwaike).setOnClickListener(onClickListener);	
		
		View view2 = LayoutInflater.from(context).inflate(R.layout.home_dept_second, null);
		
		view2.findViewById(R.id.dpt_zhengxingwaike).setOnClickListener(onClickListener);
		view2.findViewById(R.id.dpt_yanke).setOnClickListener(onClickListener);
		view2.findViewById(R.id.dpt_erbihouke).setOnClickListener(onClickListener);
		view2.findViewById(R.id.dpt_hemianwaike).setOnClickListener(onClickListener);
		view2.findViewById(R.id.dpt_fuke).setOnClickListener(onClickListener);
		view2.findViewById(R.id.dpt_xiaoerke).setOnClickListener(onClickListener);	
		
		//View view3 = LayoutInflater.from(context).inflate(R.layout.home_dept_third, null);
		
		pageViews = new ArrayList<View>();
		pageViews.add(view1);
		pageViews.add(view2);
		//pageViews.add(view3);
		
		dept_viewpager = (ViewPager) mView.findViewById(R.id.dept_viewpager);
		iv_1 = (ImageView)mView.findViewById(R.id.iv_1); 
	    iv_2 = (ImageView)mView.findViewById(R.id.iv_2); 
	    //iv_3 = (ImageView)mView.findViewById(R.id.iv_3); 
	    
	    deptPageAdapter = new DeptPageAdapter();
	    dept_viewpager.setAdapter(deptPageAdapter);
	    
		dept_viewpager.addOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				if (arg0 == 0) {
	        		iv_1.setImageResource(R.drawable.home_vp_s);
	        		iv_2.setImageResource(R.drawable.home_vp_n);
	        		//iv_3.setImageResource(R.drawable.home_vp_n);
	        		
				}else if (arg0 == 1) {
					iv_1.setImageResource(R.drawable.home_vp_n);
	        		iv_2.setImageResource(R.drawable.home_vp_s);
	        		//iv_3.setImageResource(R.drawable.home_vp_n);
				}
//				else if (arg0 == 2) {
//					iv_1.setImageResource(R.drawable.home_vp_n);
//	        		iv_2.setImageResource(R.drawable.home_vp_n);
//	        		iv_3.setImageResource(R.drawable.home_vp_s);
//				}
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	
	
	private void toDeptToHospitalActivity(int id) {
		if (scalpelEntity2 != null) {
			DisNavsEntity disNavsEntity = null;
			switch (id) {
				case R.id.dpt_waike:
					disNavsEntity = mapDisNav.get("普外科");
					
					break;
				case R.id.dpt_guke:
					disNavsEntity = mapDisNav.get("骨科");
					
					break;
				case R.id.dpt_shenjingwaike:
					disNavsEntity = mapDisNav.get("神经外科");
					
					break;
				case R.id.dpt_miniaowaike:
					disNavsEntity = mapDisNav.get("泌尿外科");
					
					break;
				case R.id.dpt_xiongwaike:
					disNavsEntity = mapDisNav.get("胸外科");
					
					break;
				case R.id.dpt_xinxueguanwaike:
					disNavsEntity = mapDisNav.get("心血管外科");
					
					break;
					
				case R.id.dpt_zhengxingwaike:
					disNavsEntity = mapDisNav.get("整形外科");
					break;
				case R.id.dpt_yanke:
					disNavsEntity = mapDisNav.get("眼科");
					break;
				case R.id.dpt_erbihouke:
					disNavsEntity = mapDisNav.get("耳鼻喉科");
					
					break;
				case R.id.dpt_hemianwaike:
					disNavsEntity = mapDisNav.get("颌面外科");
					
					break;
				case R.id.dpt_fuke:
					disNavsEntity = mapDisNav.get("妇科");
					break;
				case R.id.dpt_xiaoerke:
					disNavsEntity = mapDisNav.get("小儿外科");
					break;	
					
				default:
					break;
			}
			if (disNavsEntity!=null) {
				Bundle bundle = new Bundle();
				bundle.putSerializable("disNavsEntity",(Serializable) disNavsEntity);
				//IntentHelper.getInstance(getActivity()).gotoActivity(DeptToHospitalActivity.class, bundle);
				IntentHelper.getInstance(getActivity()).gotoActivity(DeptToHospitalActivityTemp2.class, bundle);
				
			}else {
				Toast.makeText(context, "数据未加载完毕！", 0).show();
			}
			
		} else {
			Toast.makeText(context, "数据未加载完毕！", 0).show();
		}
	}
	
	private void doNet() {
		LoadingDialog.getInstance(activity).show();
		String actionUrl = Constants.baseURL + "appnav1";// + "&api=6"
		getHttpResult(actionUrl, Constants.HTTP_INDEX.First, new TypeToken<QjResult<ScalpelEntity>>() {});
		
		
		String categorydiseaseUrl = Constants.baseURL + "categorydisease";// + "&api=6"
		getHttpResult(categorydiseaseUrl, Constants.HTTP_INDEX.Second, new TypeToken<QjResult<ScalpelEntity>>() {});
	}
	
	@Override
	public void onSuccess(QjResult result, String flg) {
		super.onSuccess(result, flg);
		try{
			
			if(flg.equals(Constants.HTTP_INDEX.First)){
			scalpelEntity = (ScalpelEntity) result.getResults();
			if (scalpelEntity != null) {
				ll_bottom.setVisibility(View.VISIBLE);
//				putMap(scalpelEntity.getDisNavs());
				Utils.saveDataToCache(
						HomeFragment.class.getSimpleName(),
						scalpelEntity);
				
				CommonUtils.setBenefitUrl(activity, scalpelEntity.url.getBenefit());
				
				
				List<BannerEntity> banners = scalpelEntity.getBanners();
				if (banners != null) {
					mCounselViewPagerAdapter = new AdViewPagerAdapter(context, banners);
					advice_viewpager.stopAutoCycle();
					advice_viewpager.setAdapter(mCounselViewPagerAdapter);
					advice_viewpager.startAutoCycle();
				}
			}else {
				Toast.makeText(context, "数据加载失败！", 0).show();
			}
			}else if (flg.equals(Constants.HTTP_INDEX.Second)) {
				scalpelEntity2 = (ScalpelEntity) result.getResults();
				if (scalpelEntity2 != null) {
					putMap(scalpelEntity2.getDisNavs());
					Utils.saveDataToCache(deptData,scalpelEntity2);
					deptPageAdapter = new DeptPageAdapter();
					dept_viewpager.setAdapter(deptPageAdapter);
				}
				
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	@Override
	public void onCompleted(Exception e, String flg) {
		super.onCompleted(e, flg);
		LoadingDialog.getInstance(activity).dismiss();
	}
	
	private void putMap(List<DisNavsEntity> disNavs){
		if(disNavs == null || disNavs.size() == 0) return;
		mapDisNav.clear();
		for (DisNavsEntity disNavsEntity : disNavs) {
			String key = disNavsEntity.getName();
			if(!mapDisNav.containsKey(key)){
				mapDisNav.put(key, disNavsEntity);
			}
		}
		
	}

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			switch (arg0.getId()) {
			case R.id.go_doctor:
				if (scalpelEntity != null&&scalpelEntity.url!=null) {
					Bundle bundle = new Bundle();
					bundle.putSerializable(Constants.ACTION_URL_DISNAVS,(Serializable) scalpelEntity.getDisNavs());
					bundle.putString(Constants.PARM_ACTION_URL, scalpelEntity.url.getDoctor());
				//	bundle.putString(Constants.PARM_ACTION_URL, "http://api.mingyizhudao.com/api2/doctor");
					
					IntentHelper.getInstance(getActivity()).gotoActivity(DoctorListActivity.class, bundle);

				} else {
					Toast.makeText(context, "数据未加载完毕！", 0).show();
				}
				break;
			case R.id.go_benefit:
				if (scalpelEntity != null&&scalpelEntity.url!=null) {
				Bundle bundle = new Bundle();
				//bundle.putString(Constants.PARM_ACTION_URL, "http://192.168.11.106/m.mingyizhudao.com/mobile/booking/test");
				//bundle.putString(Constants.PARM_ACTION_URL, "http://192.168.11.219/m.myzd.com/mobile/questionnaire/beginQuestionnaireView?appId=ddaa785817d165e8&site=1&app=1&os=android");
				//bundle.putString(Constants.PARM_ACTION_URL, "http://m.mingyizhudao.com/mobile/questionnaire/beginQuestionnaireView?appId=6fbe6269c56d4ffa&site=3");
				
				
				bundle.putString(Constants.PARM_ACTION_URL, "http://m.mingyizhudao.com/mobile/event/view/page/mygy/header/0");
				bundle.putString(Constants.PARM_PAGE_TITLE, "公益手术");
				
				IntentHelper.getInstance(activity).gotoActivity(WebViewActivity.class, bundle);
				}
				else {
					Toast.makeText(context, "数据未加载完毕！", 0).show();
				}
				break;
			case R.id.go_fast_booking:
				if (scalpelEntity != null&&scalpelEntity.url!=null) {
				IntentHelper.getInstance(activity).gotoActivityWithURL(
						FastBookingActivity.class, scalpelEntity.url.getQuickbooking());
				}
				else {
					Toast.makeText(context, "数据未加载完毕！", 0).show();
				}
				break;
			
			case R.id.search:
				if (scalpelEntity != null) {
					Bundle bundle = new Bundle();
					bundle.putSerializable(Constants.ACTION_URL_DISNAVS,(Serializable) scalpelEntity.getDisNavs());
					bundle.putString(Constants.PARM_ACTION_URL, scalpelEntity.url.getDoctor());
					
					IntentHelper.getInstance(getActivity()).gotoActivity(SearchActivity.class, bundle);

				} else {
					Toast.makeText(context, "数据未加载完毕！", 0).show();
				}
				break;	
			default:
				toDeptToHospitalActivity(arg0.getId());
				break;
			}
		}
	};
	
	@Override
	public void onPause() {
		super.onPause();
		if (advice_viewpager != null)
			advice_viewpager.stopAutoCycle();
	}

	
	class DeptPageAdapter extends PagerAdapter{
		//销毁position位置的界面
		@Override
		public void destroyItem(View v, int position, Object arg2) {

			((ViewPager)v).removeView(pageViews.get(position));
		}
		@Override
		public void finishUpdate(View arg0) {

		}
		//获取当前窗体界面数
		@Override
		public int getCount() {

			return pageViews.size();
		}

		//初始化position位置的界面
		@Override
		public Object instantiateItem(View v, int position) {
			// TODO Auto-generated method stub
			((ViewPager) v).addView(pageViews.get(position));  
			
			return pageViews.get(position);  
		}


		// 判断是否由对象生成界面
		@Override
		public boolean isViewFromObject(View v, Object arg1) {
			// TODO Auto-generated method stub
			return v == arg1;
		}

		@Override
		public int getItemPosition(Object object) {
			return super.getItemPosition(object);
		}

	}
	
	
}
